/**
 * plupload插件    单文件上传   方法封装
 * Created by kroyo
 * Date: 2018/3/1
 * Time: 9:38
 * version ： 0.0.1
 * 
 * 使用方法：
 * 	   1. 在input中添加 类“upload-file”  如下： <input type="text" class="upload-file" value="">   该input就是储存file-url的input
 *     2. 这样就形成的一个单文件上传的控件, 即该input会被隐藏，显示的是一个“上传”按钮
 *     3. 文件上传成功后，file-url储存在该input的value中
 * 	   4. 目前还没设置上传进度
 */


$.fn.extend({
	single_uploadfile:function(object){
		var pickfiles = this[0].id,
			accessid = '',
	        accesskey = '',
	        host = '',
	        policyBase64 = '',
	        signature = '',
	        callbackbody = '',
	        filename = '',
	        key = '',
	        expire = 0,
	        g_object_name = '',
	        g_object_name_type = 'random_name',
	        now = timestamp = Date.parse(new Date()) / 1000;

        function send_request() {
            var xmlhttp = null;
            if(window.XMLHttpRequest)
            {
                xmlhttp = new XMLHttpRequest();
            } else if(window.ActiveXObject)
            {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            if(xmlhttp != null)
            {
                serverUrl = 'http://api.storage.laisj.com/get.php';
                xmlhttp.open( "GET", serverUrl, false );
                xmlhttp.send( null );
                return xmlhttp.responseText
            } else {
                alert("Your browser does not support XMLHTTP.");
            }
        };

        function get_signature() {
            //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
            now = timestamp = Date.parse(new Date()) / 1000;
            if(expire < now + 3) {
                body = send_request()
                var obj = eval("(" + body + ")");
                host = obj['host']
                policyBase64 = obj['policy']
                accessid = obj['accessid']
                signature = obj['signature']
                expire = parseInt(obj['expire'])
                callbackbody = obj['callback']
                key = obj['dir']
                return true;
            }
            return false;
        };

        function random_string(len) {
            len = len || 32;
            var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
            var maxPos = chars.length;
            var pwd = '';
            for(i = 0; i < len; i++) {
                pwd += chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return pwd;
        }

        function get_suffix(filename) {
            pos = filename.lastIndexOf('.')
            suffix = ''
            if(pos != -1) {
                suffix = filename.substring(pos)
            }
            return suffix;
        }

        function calculate_object_name(filename) {
            if(g_object_name_type == 'local_name') {
                g_object_name += "${filename}"
            } else if(g_object_name_type == 'random_name') {
                suffix = get_suffix(filename)
                g_object_name = key + random_string(10) + suffix
            }
            return ''
        }

        function get_local_object_name(filename) {
            return filename.name
        }

        function get_uploaded_object_name(filename) {
            if(g_object_name_type == 'local_name') {
                tmp_name = g_object_name
                tmp_name = tmp_name.replace("${filename}", filename);
                return tmp_name
            } else if(g_object_name_type == 'random_name') {
                return g_object_name
            }
        }

        function set_upload_param(up, filename, ret) {
            if(ret == false) {
                ret = get_signature()
            }
            g_object_name = key;
            if(filename != '') {
                suffix = get_suffix(filename)
                calculate_object_name(filename)
            }
            new_multipart_params = {
                'key': g_object_name,
                'policy': policyBase64,
                'OSSAccessKeyId': accessid,
                'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                'callback': callbackbody,
                'signature': signature,
            };

            up.setOption({
                'url': host,
                'multipart_params': new_multipart_params
            });

            up.start();
        }
        
        //判断变量是否为空或不存在
		var isset = function(protype){
			return (typeof(protype) != 'undefined' && protype != '')
		}
		
		//1.重写属性
		//1.1重写文件过滤
		var filters = {
				max_file_size : '1000mb',              //文件最大为10mb
				prevent_duplicates : false          //允许选取重复文件
			},
			type = 'single',                         //single : 单个  ；     multi ： 多个
			multi_selection = false,
			file_url = {};                     //多个文件上传url存储
		if(isset(object)){
			if(isset(object.filters)){
				filters = object.filters;
			}
			//1.2 确定文件上传是  单个还是多个 
			if(isset(object.type)){
				type = object.type;
			}
			if(isset(object.type)&&object.type == 'multi'){
				multi_selection = true;
			}
		}
		

        var uploader = new plupload.Uploader({
			runtimes : 'html5,html4',    
			browse_button : pickfiles,     				//上传文件按钮
			multi_selection : multi_selection,          			//是否可以在文件浏览对话框中选择多个文件，true为可以，false为不可以
			url : 'http://oss.aliyuncs.com',             //服务器端的上传页面地址
			flash_swf_url : '../js/Moxie.swf',
			silverlight_xap_url : '../js/Moxie.xap',
			
			//1.1文件过滤
			filters : filters,
			
			//1.2 init
			init : {
				PostInit: function(){
					$('body').append('<input id="url-finance" type="text" value="">');
				},
				
				FilesAdded: function(up, files){
					var html = null;
					if($('.fileupload-wrapper').length>0&&type!='multi'){
                        $('.fileupload-wrapper').remove();
                        //清空file_url
                        for(var key in file_url){
							delete file_url[key];
						}
                    }
					plupload.each(files, function(file) {
                        set_upload_param(uploader, '', false);
					});
				},
				
				BeforeUpload: function(up, file) {
	                set_upload_param(up, file.name, true);
	            },
				
				UploadProgress: function(up, file){
					var progBar = $('#'+file.id).find('.progress-bar');
					if(progBar) {
						progBar.css('width',file.percent+'%');
					}
				},
				FileUploaded: function(up,file,info){
					if(info.status != 200) {
						return false;
					}
					var fileurl = get_uploaded_object_name(file);
					$('#url-finance').val(fileurl);

					var $logo = $('.logo-wrapper img'),
                        $img = $('.item-license .img-wrapper img');
					if($logo.length>0){
                        $logo.prop('src','http://laisheji-file.oss-cn-shenzhen.aliyuncs.com/'+fileurl);
                        successbox("公司标识上传成功");
                    }
                    if($img.length>0){
                        $img.prop('src','http://laisheji-file.oss-cn-shenzhen.aliyuncs.com/'+fileurl);
                        $('.win-imgwrapper img').prop('src','http://laisheji-file.oss-cn-shenzhen.aliyuncs.com/'+fileurl);
                        $('.item-license .img-wrapper').css('display','block');
                    }
				},
				Error:function(up,err){
					if(err.code == -602) {
						alertbox('这个文件已经上传过一遍了')
					}
					if(err.code == -601) {
						alertbox('不支持该类型的文件上传')
					}
					if(err.code == -600) {
						alertbox('文件大小超出限制')
					}
				}
			}
		});
        uploader.init();
        return uploader;
	}
});


